<?php

class ModelAction extends PublicAction
{
    protected $db;
    protected $path;

    function _initialize()
    {
        parent::_initialize();
        $this->path = APP_PATH . 'Lib/Field/';
        $this->db = D('Model');
        $this->Role = getCache('Role');
        $this->assign('Role', $this->Role);
    }

    function index()
    {
        if ($_REQUEST ['type']) {
            $_REQUEST['where'] = 'type=' . intval($_REQUEST ['type']);
        } else {
            $_REQUEST['where'] = 'type=1';
        }

        $model_db = M('Model');
        if (empty($_REQUEST['where'])) {
            $list = $model_db->select();
        } else {
            $list = $model_db->where($_REQUEST['where'])->select();
        }

        //记录当前位置
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $this->assign('list', $list);
        $this->display();
    }

    function add()
    {
        if (empty($_GET['type']))
            $_GET['type'] = 1;
        $this->display();
    }

    function edit()
    {
        $model_db = M('Model');
        $id = I('get.id', 0, 'intval');

        if (empty($id))
            $this->error('缺少必要的参数!');

        $vo = $model_db->getById($id);

        $this->assign('vo', $vo);
        $this->display();
    }

    function update()
    {
        $model_db = D('Model');

        if (false === $model_db->create()) {
            $this->error($model_db->getError());
        }

        if (false !== $model_db->save()) {

            saveCache('Model');

            $this->success('修改成功!', cookie('__forward__'));
        } else {
            $this->error('修改失败!: ' . $model_db->getDbError());
        }
    }

    function insert()
    {
        $tablename = I('post.tablename');
        $tablename = C('DB_PREFIX') . strtolower($tablename);

        D('');
        $db = DB::getInstance();
        $tables = $db->getTables();
        if (in_array($tablename, $tables)) {
            $this->error('此模型已存在!');
        }

        $_POST['tablename'] = ucfirst($_POST['tablename']);
        $model_db = $this->db;
        if (false === $model_db->create()) {
            $this->error($model_db->getError());
        }
        $modelid = $model_db->add();
        if (empty($modelid))
            $this->error('提交失败！: ' . $model_db->getDbError());

        $field_db = D('Field');
        if (empty($_POST['emptytable'])) {
            $db->execute("CREATE TABLE `" . $tablename . "` (
                `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
                `catid` smallint(5) unsigned NOT NULL DEFAULT '0',
                `user_id` int(8) unsigned NOT NULL DEFAULT '0',
                `username` varchar(40) NOT NULL DEFAULT '',
                `title` varchar(120) NOT NULL DEFAULT '',
                `title_style` varchar(40) NOT NULL DEFAULT '',
                `thumb` varchar(100) NOT NULL DEFAULT '',
                `keywords` varchar(120) NOT NULL DEFAULT '',
                `description` text NOT NULL,
                `content` mediumtext NOT NULL,
                `url` varchar(60) NOT NULL DEFAULT '',
                `template` varchar(40) NOT NULL DEFAULT '',
                `posid` varchar(50) NOT NULL DEFAULT '',
                `status` tinyint(1) unsigned NOT NULL DEFAULT '0',
                `recommend` tinyint(1) unsigned NOT NULL DEFAULT '0',
                `listorder` int(10) unsigned NOT NULL DEFAULT '0',
                `hits` int(11) unsigned NOT NULL DEFAULT '0',
                `create_time` int(11) unsigned NOT NULL DEFAULT '0',
                `update_time` int(11) unsigned NOT NULL DEFAULT '0',
                `lang` tinyint(1) unsigned NOT NULL DEFAULT '0',
                PRIMARY KEY (`id`),
                KEY `status` (`id`,`status`,`listorder`),
                KEY `catid` (`id`,`catid`,`status`),
                KEY `listorder` (`id`,`catid`,`status`,`listorder`)
              ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8");

            $field_arr = ['catid', 'title', 'thumb', 'keywords', 'description', 'create_time', 'content', 'hits', 'posid', 'recommend', 'template', 'status'];

            foreach ($field_arr as $field) {
                $model_filed = include($this->path . $field . '.php');
                $model_filed['modelid'] = $modelid;
                $field_db->add($model_filed);
            }

        } else {
            $db->execute("CREATE TABLE `" . $tablename . "` (
                `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
                `status` tinyint(1) unsigned NOT NULL DEFAULT '0',
                `user_id` int(8) unsigned NOT NULL DEFAULT '0',
                `url` varchar(60) NOT NULL DEFAULT '',
                `listorder` int(10) unsigned NOT NULL DEFAULT '0',
                `create_time` int(11) unsigned NOT NULL DEFAULT '0',
                `update_time` int(11) unsigned NOT NULL DEFAULT '0',
                PRIMARY KEY (`id`)
            ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8");
            $model_filed = include($this->path . 'create_time.php');
            $model_filed['modelid'] = $modelid;
            $field_db->add($model_filed);
            $model_filed = include($this->path . 'status.php');
            $model_filed['modelid'] = $modelid;
            $field_db->add($model_filed);
        }

        if ($modelid !== false) {

            //新增相应菜单
            $menu_db = M('auth_rule');
            $data = [
                'pid' => 44,
                'name' => 'Admin/'.$_POST['tablename'].'/index',
                'title' => $_POST['name'],
                'sort' => 0,
                'status' => 1,
                'ismenu' => 1,
                'icon' => 'fa fa-circle-o'
            ];
            $ruleId = $menu_db->data($data)->add();

            $data = [
                'pid' => $ruleId,
                'name' => 'Admin/'.$_POST['tablename'].'/add',
                'status' => 1,
                'title' => '新增'
            ];
            $menu_db->data($data)->add();

            $data = [
                'pid' => $ruleId,
                'name' => 'Admin/'.$_POST['tablename'].'/edit',
                'status' => 1,
                'title' => '编辑'
            ];
            $menu_db->data($data)->add();

            $data = [
                'pid' => $ruleId,
                'name' => 'Admin/'.$_POST['tablename'].'/delete',
                'status' => 1,
                'title' => '删除'
            ];
            $menu_db->data($data)->add();

            $data = [
                'pid' => $ruleId,
                'name' => 'Admin/'.$_POST['tablename'].'/setStatus',
                'status' => 1,
                'title' => '更改状态'
            ];
            $menu_db->data($data)->add();

            $data = [
                'pid' => $ruleId,
                'name' => 'Admin/'.$_POST['tablename'].'/remove',
                'status' => 1,
                'title' => '移动'
            ];
            $menu_db->data($data)->add();

            $data = [
                'pid' => $ruleId,
                'name' => 'Admin/'.$_POST['tablename'].'/sort',
                'status' => 1,
                'title' => '排序'
            ];
            $menu_db->data($data)->add();

            $data = [
                'pid' => $ruleId,
                'name' => 'Admin/'.$_POST['tablename'].'/push',
                'status' => 1,
                'title' => '推送'
            ];
            $menu_db->data($data)->add();
            
            saveCache('Model');
            saveCache('Field', $modelid);
            $this->success('添加成功！', cookie('__forward__'));
        } else {
            $this->error('提交失败！: ' . $model_db->getDbError());
        }
    }

    function delete()
    {
        $model_db = D('Model');
        $id = I('get.id', 0, 'intval');
        $r = $model_db->find($id);
        if (empty($r))
            $this->error('缺少必要的参数!');

        $tablename = $model_db->where('id=' . $id)->getField('tablename');
        $realTableName = C('DB_PREFIX') . strtolower($tablename);
        $m = $model_db->delete($id);
        if ($m) {
            $model_db->execute("DROP TABLE IF EXISTS `" . $realTableName . "`");
            $modelname = ucfirst($tablename);
            $menu_db = M('auth_rule');
            $menu_db->where(['name'=>['like','Admin/' . $modelname . '%']])->delete();
            $field_db = M('Field');
            $field_db->where('modelid=' . $id)->delete();

            saveCache('Model');
            saveCache('Menu');
            @unlink(RUNTIME_PATH . 'Data/Field_' . $id . '.php');
            $this->success('操作成功！');
        }
    }

    /*状态*/
    public function status()
    {
        $model_db = D('Model');
        if ($model_db->save($_GET)) {
            saveCache('Model');
            $this->success('提交成功!');
        } else {
            $this->error('提交失败！');
        }
    }

    //获取当前菜单id和子栏目id
    function getStrChildId($id)
    {
        $node_db = M('Node');
        $strChildId = $id;
        $list = $node_db->where('pid=' . $id)->select();
        if (!empty($list)) {
            foreach ($list as $val) {
                $strChildId = $strChildId . ',' . $this->getStrChildId($val['id']);
            }
        }

        return $strChildId;
    }
}